import sys
import clips
import wx
import glob
import os
from ExplanationFrame import ExplanationFrame
from eRecruiterObjects import *
from eRecruiterFrame import eRecruiterFrame
from ImportanceFrame import ImportanceFrame
from eRecruiterObjects import AreaWeightObject
from Resume import *

class eRecruiter(wx.App):
    def OnInit(self):

        """Load Base Clips files"""
        clips.Clear()
        clips.Load('TemplatesandRules2.clp')
        clips.Load('ComputerScienceSchoolFacts.clp')
        clips.DebugConfig.EnvironmentErrorsEnabled = True
        clips.DebugConfig.WatchAll()

        
        """Load Resume Clips files """       
        """path = "RESUME_FACTS/"
        for infile in glob.glob(os.path.join(path, '*.clp')):
            clips.Load(infile)
            print "loading " + infile

        print clips.PrintFacts()
        
        #Run Clips
        clips.Reset()
        clips.Run()
        print clips.PrintFacts()
        print clips.PrintRules()
        f_list = clips.Eval("(find-all-facts ((?f SkillsExp)) (eq ?f:skill c++))")
        for fact in f_list:
            print fact.PPForm()
            
        x = clips.FactList()

        print x[1].PPForm()
        """
        
        self.eRec = eRecruiterFrame()
        
        self.eRec.findBTN.Bind(wx.EVT_BUTTON, self.FindMatches)
        self.eRec.resetBTN.Bind(wx.EVT_BUTTON, self.ResetClips)
        
        self.eRec.Show()
        return True

    def exit(self, event):
        sys.exit(0)

    def GetValues(self, event):
        self.area_weights = self.importanceDia.GetAreaDictionary()
        print self.area_weights.AreasOfExpertise
        self.importanceDia.Close()
        return True
    
    def FindMatches(self, event):
        
            
        #get rankings
        areas = []
        if self.eRec.ldrExperCHK.IsChecked():
            areas.append('Leadership')
        if self.eRec.desCertCHK.IsChecked():
            areas.append('Certifications')
        if self.eRec.desSkillsCHK.IsChecked():
            areas.append('Skills')
        if self.eRec.desEduCHK.IsChecked():
            areas.append('Education')
        if self.eRec.desWorkAreaCHK.IsChecked():
            areas.append('AreasOfExpertise')
        if len(areas) > 0:
            self.importanceDia = ImportanceFrame(areas)
            self.importanceDia.findBTN.Bind(wx.EVT_BUTTON, self.GetValues)
            #show modal will wait till we click ok or (x)
            self.importanceDia.ShowModal()
        else:
            self.area_weights = AreaWeightObject()

        #get keywords out of out of self.area_weights and from the UI - then pass them to weis part

                
        generalKeywords = self.eRec.RetrieveKeywords()

        #TODO - pass keywords
        path = "RESUMES/"
        for infile in glob.glob(os.path.join(path, '*.html')):
            print "parsing:  " + infile
            reload(sys)
            sys.setdefaultencoding("utf-8")
            print os.path.basename(infile).split('.')[0]
            Resume(os.path.basename(infile).split('.')[0],infile,generalKeywords)

            
        minGPA = self.eRec.RetrieveMinGPA()
        years_exp = self.eRec.RetrieveYearsExpereience()
        reqSkills = self.eRec.RetrieveRequiredSkills()
        desSkills = self.eRec.RetrieveDesiredSkills()
        education = self.eRec.RetrieveEducationLevel()
        certs = self.eRec.RetrieveCertifications()

        year_exp_fact = ' (MinYearExp %s) ' %(str(float(years_exp[0]*12)))
        year_exp_fact += ' (MaxYearExp %s) ' %(str(float(years_exp[1]*12)))
        clips.BuildDeffacts("yearsExper",year_exp_fact)
        
        gpa_fact = ' (ReqGPA %s) ' %(minGPA)
        clips.BuildDeffacts("requiredGPA",gpa_fact)
        
        if self.area_weights.Education is not None:
            if len(self.area_weights.Education[0]) > 0:
                fact = ""
                for s in self.area_weights.Education[0]:
                    fact += ' (ReqMaj \"%s\") ' %(s)
                clips.BuildDeffacts("requiredMajors",fact)
            if len(self.area_weights.Education[2]) > 0:
                fact = ""
                for s in self.area_weights.Education[2]:
                    fact += ' (DesiredMaj \"%s\") ' %(s)
                clips.BuildDeffacts("desMajors",fact)
        
        if len(reqSkills) > 0:
            print "---Required Skills---"
            fact = ""
            for s in reqSkills:
                fact += " (ReqSkill \"%s\") " %(s)
                print s
            clips.BuildDeffacts("requiredSkills",fact)
            
        if len(desSkills) > 0:
            print "---Desired Skills---"
            fact = ""
            for s in desSkills:
                fact += " (PrefSkill \"%s\") " %(s)
                print s
            clips.BuildDeffacts("desiredSkills",fact)
            clips.BuildGlobal("MaxSkill", len(desSkills))
            print len(desSkills)
        else:
            clips.BuildGlobal("MaxSkill", 1)
            
        
        if self.area_weights.AreasOfExpertise is not None:
            if len(self.area_weights.AreasOfExpertise[0]) > 0:
                fact = ""
                for s in self.area_weights.AreasOfExpertise[0]:
                    fact += " (ReqWA \"%s\") " %(s)
                clips.BuildDeffacts("reqWA",fact)

            if len(self.area_weights.AreasOfExpertise[1]) > 0:
                fact = ""
                for s in self.area_weights.AreasOfExpertise[1]:
                    fact += " (PrefWA \"%s\") " %(s)
                clips.BuildDeffacts("prefWA",fact)
                clips.BuildGlobal("MaxWorkArea",len(self.area_weights.AreasOfExpertise[1]))
            else:
                clips.BuildGlobal("MaxWorkArea",1)
           
        print "---Required Education Level---"
        edu_facts = " (MinEducationLevel  %s) " % (str(float(education[1])))
        edu_facts += " (MaxEducationLevel %s) " % (str(float(education[0])))

        
        clips.BuildDeffacts("requiredDegreeLevel", edu_facts)

        if len(certs[1]) > 0:
            cert = ""
            print "---Required Certifications---"
            for s in certs[1]:
                cert += " (ReqCert \"%s\") " % (s)
                print s
            clips.BuildDeffacts("requiredCerts", cert)
        non_req_certs = list(set(certs[0]) - set(certs[1]))
        if len(non_req_certs) > 0:
            print "---Desired Certifications---"
            cert = ""
            for s in non_req_certs:
                cert += " (PrefCert \"%s\") " %(s)
                print s 
            clips.BuildDeffacts("desiredCerts", cert)
            clips.BuildGlobal("MaxCertification",len(non_req_certs))
        else:
            clips.BuildGlobal("MaxCertification",1)


        cert_val = 0
        AOE_val = 0
        loyal_val = 0
        edu_val = 0
        skill_val = 0
        ldr_val = 0
        
        if 'AreasOfExpertise' in areas:
            AOE_val =  self.area_weights.AreasOfExpertise[2]
            
        if 'Education' in areas:
            edu_val = self.area_weights.Education[1]
            
        if 'Certifications' in areas:
            cert_val = self.area_weights.Certs[1]
            
        if 'Skills' in areas:
            skill_val = self.area_weights.Skills[1]
            
        if 'Leadership' in areas:
            ldr_val = self.area_weights.Leadership[1]

        total = AOE_val + ldr_val + skill_val + cert_val + edu_val

        if total == 0:
            total = 1
        
        clips.BuildGlobal("WorkArea%Total",100.0*AOE_val/total)
        clips.BuildGlobal("Leadership%Total",100.0*ldr_val/total)
        clips.BuildGlobal("Skill%Total",100.0*skill_val/total)
        clips.BuildGlobal("Certification%Total",100.0*cert_val/total)
        clips.BuildGlobal("Degree%Total",100.0*edu_val/total)
        
        matches = []

        path = "clps/"
        for infile in glob.glob(os.path.join(path, '*.clp')):
            clips.Load(infile)
            print "loading " + infile


        clips.PrintAgenda()
        clips.Reset()
        clips.Run()
        print clips.ErrorStream.Read()
        print clips.PrintFacts()
        

        
        people_facts = clips.Eval("(find-all-facts ((?f Person)) TRUE)")
        for person in people_facts:
            score = 0
            if person.Slots['SkillScore'] < 0 or person.Slots['EducationScore'] < 0 or person.Slots['CertificationScore'] < 0 or person.Slots['WorkAreaScore'] < 0 or person.Slots['DegreeScore'] < 0 or person.Slots['TotalYears'] < 0:
                score = -1
            else:
                score = float(person.Slots['TotalScore'])


                if 'Skills' in areas:
                    if person.Slots['SkillScore'] < (self.area_weights.Skills[0]*skill_val/total):
                        score -= float(person.Slots['SkillScore'])
                else:
                    score -= float(person.Slots['SkillScore'])
                if 'Leadership' in areas:
                    if person.Slots['LeadershipScore'] < (self.area_weights.Leadership[0]*ldr_val/total):
                        score -= float(person.Slots['LeadershipScore'])
                else:
                    score -= float(person.Slots['LeadershipScore'])
                if 'Certifications' in areas:
                    if person.Slots['CertificationScore'] < (self.area_weights.Certs[0]*cert_val/total):
                        score -= float(person.Slots['CertificationScore'])
                else:
                    score -= float(person.Slots['CertificationScore'])

            try:
                keyword_facts = clips.Eval("(find-all-facts ((?f KeyWordOccurance )) (eq ?f:ID %s))" %(str(person.Slots['ID'])))
            except:
                print 'no keywords'
                keyword_facts = []
            total_keyword_occ = 0
            for key_fact in keyword_facts:
                total_keyword_occ += int(key_fact.Slots['Count'])
                print "keyfact" + str(key_fact.Slots['Count'])

            matches.append(ResultListObject(person.Slots['Name'],
                                            str(score),person.Slots['Path'].replace("RESUMES","RESUMES\\"),str(person.Slots['ID']),str(total_keyword_occ)))
        

        self.eRec.area_weights = self.area_weights
        sorted_matches = sorted(matches, key=lambda ResultListObject: float(ResultListObject.Score),reverse=True)

            
        self.eRec.DisplayResults(sorted_matches)
        self.eRec.areas = areas

    def ResetClips(self, event):
        clips.Clear()
        clips.Load('TemplatesandRules2.clp')
        clips.Load('ComputerScienceSchoolFacts.clp')
        self.eRec.DisplayResults([])

if __name__ == '__main__':
    app = eRecruiter(0)
    app.MainLoop()

    
